<script setup lang="ts">
import { reactive, ref, toRaw } from "vue";
import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
import {
  live_course_info_api,
  live_course_create_order_api,
  live_course_mini_pay_api,
} from "@/package/mall/api/guider_home";
import { previewImage } from "@/utils/meida";
import { data_api } from "@/api/my";
import { EV_LOGIN, EV_ORDER } from "@/constant/event";
import { Account } from "@/utils/account";
import { AppData } from "@/utils/app";
import { autoTask } from "@/utils/timer";
import { Date } from "@/utils/date";
import { numToHour } from "@/utils/number";
import { requestPayment } from "@/utils/payment";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import Swipe from "@/components/swipe/swipe.vue";
import DetailMenuBtn from "../goods/components/detail-menu-btn.vue";
import ServiceContact from "@/components/service/contact.vue";
import FormButton from "@/components/form/button.vue";
import PopupModal from "@/components/popup/modal.vue";

onLoad((options) => {
  live_course_info_api({ id: options?.id }).then((resp) => {
    adList.value = (resp.pic_url_arr as string[]).map((i) => {
      return { type: "img", url: i };
    });
    if (resp.video_url) {
      adList.value.unshift({
        type: "video",
        url: resp.video_url,
        poster: resp.pic_url_arr[0],
      });
    }
    infoData.price = resp.price;
    infoData.start_time = resp.start_time;
    infoData.end_time = resp.end_time;
    infoData.is_can_playback = resp.is_can_playback;
    infoData.name = resp.name;
    infoData.tag_arr = resp.tag_arr;
    infoData.sold_count_str = resp.sold_count_str;
    infoData.lecturer_pic = resp.lecturer_pic;
    infoData.lecturer_name = resp.lecturer_name;
    infoData.one_word = resp.one_word;
    infoData.content = resp.content.replace(
      /\<img/gi,
      '<img class="detail-intro-img" '
    );
    infoData.type = resp.type;

    autoTaskStop = autoTask({ delay: 1000, immediate: true }, () => {
      const current = Date.getDate();
      const timestamp = current.unix();

      const start_time = Date.getDate(infoData.start_time * 1000);
      if (timestamp > infoData.end_time) {
        // 已结束
        infoData.live_state = 2;
      } else if (timestamp < infoData.start_time) {
        // 未开始
        infoData.live_state = 0;
        const start_time_str = start_time.format(Date.ftDate);
        if (start_time_str === current.format(Date.ftDate)) {
          infoData.start_state = 1; // 今天
          infoData.start_time_arr = numToHour(
            infoData.start_time - timestamp
          ).split(":");
        } else if (
          start_time_str === current.add(1, "day").format(Date.ftDate)
        ) {
          infoData.start_state = 2; // 明天
          infoData.start_time_str = `明天 ${start_time.format("HH:mm")}`;
        } else {
          infoData.start_state = 0;
          infoData.start_time_str = `${start_time.format(
            "YYYY年M月D日 HH:mm"
          )}`;
        }
        infoData.start_time_btn = `${start_time.format("M月D日 HH:mm")} 开播`;
      } else {
        // 直播中
        infoData.live_state = 1;
      }
    });

    tempData.url = resp.url;
  });

  tempData.id = options?.id;

  Account.isLogin && reloadMyData();
  uni.$on(EV_LOGIN, evLoginCallback);
  uni.$on(EV_ORDER, evOrderCallback);
});
onShow(() => (myData.isVip = AppData.userData.is_vip_member === 1));
onUnload(() => {
  autoTaskStop?.();
  uni.$off(EV_LOGIN, evLoginCallback);
  uni.$off(EV_ORDER, evOrderCallback);
});

const adIndex = ref(0);
const adList = ref<any[]>([]);
const adClick = () => {
  const _adList = toRaw(adList.value);
  const _adIndex = toRaw(adIndex.value);
  if (_adList[_adIndex].type === "video") {
  } else {
    // 第一个是否是视频
    if (_adList[0].type === "video") {
      previewImage(
        _adList.filter((i) => i.type === "img").map((i) => i.url),
        _adIndex - 1
      );
    } else {
      previewImage(
        _adList.map((i) => i.url),
        _adIndex
      );
    }
  }
};

const infoData = reactive({
  price: "",
  start_time: 0,
  end_time: 0,
  is_can_playback: 1,
  live_state: 0,
  start_state: 0,
  start_time_str: "",
  start_time_btn: "",
  start_time_arr: [] as string[],
  name: "",
  tag_arr: [] as string[],
  sold_count_str: "",
  lecturer_pic: "",
  lecturer_name: "",
  one_word: "",
  content: "",
  type: 1,
});

const btnClick = () => {
  // 已结束、不支持回放
  if (infoData.live_state === 2 && infoData.is_can_playback !== 1) return;

  if (infoData.type === 3) {
    const fn = (isLogin: boolean) => {
      // 已购买
      if (myData.isPay)
        return infoData.live_state === 0
          ? Toast.show("直播未开始，请耐心等待哦~")
          : Router.navigateToOrRedirectTo(isLogin, tempData.url);

      isLogin && Router.navigateBack();

      // 购买
      payClick();
    };

    Account.isLogin
      ? fn(false)
      : Account.login(() => {
          reloadMyData().then(() => fn(true));
        });
  } else {
    Account.checkLogin((isLogin) => {
      const fn = () => {
        infoData.live_state === 0
          ? Toast.show("直播未开始，请耐心等待哦~")
          : Router.navigateToOrRedirectTo(isLogin, tempData.url);
      };

      if (infoData.type !== 4) return fn();

      // 是 VIP
      if (AppData.userData.is_vip_member === 1) return fn();

      isLogin && Router.navigateBack();
      popupModal.value?.show(
        {
          content:
            "该课程为VIP专属直播课，需要开通导游VIP才能观看哦，是否开通？",
          confirmText: "开通导游VIP",
        },
        () => {
          Router.navigateTo("/package/mall/pages/vip/index");
        }
      );
    });
  }
};

const payClick = () => {
  Toast.showLoading();
  live_course_create_order_api({ id: tempData.id })
    .then((resp) => {
      return live_course_mini_pay_api({ order_id: resp.order_id }).then(
        (resp) => {
          Toast.hideLoading();
          requestPayment(
            resp,
            () => {
              uni.$emit(EV_ORDER, {
                type: "pay",
                data: { type: "live", id: tempData.id },
              });
              Router.redirectTo("/package/my/pages/order/list");
            },
            () => {
              Router.redirectTo("/package/my/pages/order/list");
            }
          );
        }
      );
    })
    .catch(() => Toast.hideLoading());
};

const myData = reactive({ isPay: false, isVip: false });

const reloadMyData = () => {
  return data_api<{ live_course?: number[] }>({
    includes: "live_course",
  }).then((resp) => {
    myData.isPay = (resp.live_course || []).includes(Number(tempData.id));
  });
};
const evLoginCallback = (e: { type: "cancel" }) => {
  console.info(`触发事件：${EV_LOGIN}`, e);
  e.type === "cancel" || reloadMyData();
};
const evOrderCallback = (e: { type: "pay" }) => {
  console.info(`触发事件：${EV_ORDER}`, e);
  e.type === "pay" || reloadMyData();
};

let autoTaskStop: (() => void) | undefined = undefined;
const popupModal = ref<InstanceType<typeof PopupModal>>();

const tempData = { id: "", url: "" };
</script>

<template>
  <view class="detail-ad" @click="adClick">
    <Swipe v-model="adIndex" :listData="adList" />
  </view>

  <view class="detail-state">
    <view class="detail-state-title" v-if="infoData.type === 4">
      <image
        class="detail-state-vip"
        src="@/package/mall/static/live-detail-vip.png"
      />
      VIP免费
    </view>
    <view class="detail-state-price" v-else-if="infoData.type === 3">
      <text class="detail-state-price2">¥</text>{{ infoData.price }}
    </view>
    <view class="detail-state-title" v-else>
      {{ infoData.type === 1 ? "免费" : "公益直播" }}
    </view>

    <view class="detail-state-content">
      <view class="detail-state-value" v-if="infoData.live_state === 2">
        直播已结束
      </view>
      <template v-else-if="infoData.live_state === 1">
        <view class="detail-state-play">
          <image class="detail-state-play2" src="/static/index-live-play.gif" />
        </view>
        <view class="detail-state-value">正在直播</view>
      </template>
      <template v-else>
        <template v-if="infoData.start_state === 1">
          <view class="detail-state-value">距直播开始</view>&nbsp;
          <view class="detail-state-date2">
            {{ infoData.start_time_arr[0] }}
          </view>
          <view class="detail-state-date3">:</view>
          <view class="detail-state-date2">
            {{ infoData.start_time_arr[1] }}
          </view>
          <view class="detail-state-date3">:</view>
          <view class="detail-state-date2">
            {{ infoData.start_time_arr[2] }}
          </view>
        </template>
        <template v-else>
          <view class="detail-state-value">直播时间</view>
          <view class="detail-state-date">{{ infoData.start_time_str }}</view>
        </template>
      </template>
    </view>
  </view>

  <view class="detail-info">
    <view class="detail-info-name">{{ infoData.name }}</view>
    <view style="display: flex; align-items: center">
      <view class="detail-info-tag" v-for="i of infoData.tag_arr" :key="i">
        {{ i }}
      </view>
      <view class="detail-info-sale">{{ infoData.sold_count_str }}</view>
    </view>
  </view>

  <view class="detail-guider">
    <view class="detail-guider-label">讲师</view>
    <image
      class="detail-guider-avatar"
      :src="infoData.lecturer_pic"
      mode="aspectFill"
    />
    <view class="detail-guider-name">{{ infoData.lecturer_name }}</view>
    <view class="detail-guider-desc">｜{{ infoData.one_word }}</view>
  </view>

  <view class="detail-intro">
    <view class="detail-intro-title">产品详情</view>
    <view class="detail-intro-html">
      <rich-text :nodes="infoData.content" />
    </view>
  </view>

  <view class="detail-fixed">
    <view class="detail-fixed-menu">
      <DetailMenuBtn
        icon="/package/mall/static/goods-contact.png"
        text="咨询"
      />
      <ServiceContact />
    </view>
    <view class="detail-fixed-btn" @click="btnClick">
      <template v-if="infoData.live_state === 2">
        <!-- 已结束 -->
        <template v-if="infoData.is_can_playback === 1">
          <FormButton v-if="infoData.type === 4">
            {{ myData.isVip ? "查看回放" : "开通VIP观看回放" }}
          </FormButton>
          <FormButton v-else-if="info.type === 3">
            {{ myData.isPay ? "查看回放" : "付费后可观看回放" }}
          </FormButton>
          <FormButton v-else>查看回放</FormButton>
        </template>
        <FormButton v-else disabled>已结束</FormButton>
      </template>
      <template v-else>
        <FormButton v-if="infoData.type === 4">
          {{ myData.isVip ? infoData.start_time_btn : "开通VIP免费观看" }}
        </FormButton>
        <FormButton v-if="infoData.type === 3">
          {{ myData.isPay ? infoData.start_time_btn : "立即购买" }}
        </FormButton>
        <FormButton v-else>
          {{ infoData.type === 1 ? "免费" : "公益直播" }}
        </FormButton>
      </template>
    </view>
  </view>
</template>

<style lang="scss">
page {
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.detail-ad {
  position: relative;
  height: 750rpx;
}

.detail-state {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding-left: 30rpx;
  background: linear-gradient(90deg, #ff5c5b 5%, #ff9370 100%);

  .detail-state-title {
    display: flex;
    align-items: center;
    height: 50rpx;
    font-size: 36rpx;
    color: #ffffff;
    line-height: 50rpx;
    font-weight: bold;
  }

  .detail-state-vip {
    width: 36rpx;
    height: 36rpx;
    margin-right: 8rpx;
  }

  .detail-state-price {
    font-size: 52rpx;
    color: #ffffff;
    line-height: 74rpx;
    font-weight: bold;
  }

  .detail-state-price2 {
    font-size: 28rpx;
    line-height: 40rpx;
  }

  .detail-state-content {
    display: flex;
    align-items: center;
    height: 100%;
    padding-left: 50rpx;
    padding-right: 30rpx;
    margin-left: auto;
    border-radius: 50rpx 0 0 50rpx;
    background: linear-gradient(90deg, #ffe1cb 6%, #ffcdb0);
  }

  .detail-state-value {
    font-size: 26rpx;
    color: #ff3333;
    line-height: 36rpx;
    font-weight: bold;
  }

  .detail-state-play {
    padding: 2rpx;
    margin-right: 8rpx;
    border-radius: 50%;
    background: linear-gradient(126deg, #ff7822 0%, #ff1a54 100%);
  }

  .detail-state-play2 {
    display: block;
    width: 32rpx;
    height: 32rpx;
  }

  .detail-state-date {
    padding: 0 8rpx;
    margin-left: 10rpx;
    font-size: 28rpx;
    color: #ffffff;
    line-height: 44rpx;
    font-weight: bold;
    border-radius: 10rpx;
    background-color: #8f3c11;
  }

  .detail-state-date2 {
    width: 38rpx;
    font-size: 24rpx;
    color: #ffffff;
    line-height: 38rpx;
    text-align: center;
    font-weight: bold;
    border-radius: 4rpx;
    background-color: #302f30;
  }

  .detail-state-date3 {
    margin: 0 10rpx;
    font-size: 24rpx;
    color: #302f30;
    line-height: 38rpx;
  }
}

.detail-info {
  padding: 24rpx 30rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;

  .detail-info-name {
    margin-bottom: 26rpx;
    font-size: 36rpx;
    color: #333333;
    line-height: 50rpx;
    font-weight: bold;
  }

  .detail-info-tag {
    padding: 0 14rpx;
    margin-right: 20rpx;
    font-size: 24rpx;
    color: #ff7900;
    line-height: 42rpx;
    border-radius: 8rpx;
    border: 2rpx solid rgba(255, 163, 0, 0.25);
    background-color: #fff7f3;
  }

  .detail-info-sale {
    flex-shrink: 0;
    margin-left: auto;
    font-size: 24rpx;
    color: #999999;
  }
}

.detail-guider {
  display: flex;
  align-items: center;
  height: 78rpx;
  padding-left: 36rpx;
  padding-right: 30rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;

  .detail-guider-label,
  .detail-guider-name {
    flex-shrink: 0;
    font-size: 28rpx;
    color: #9f9f9f;
    line-height: 40rpx;
  }

  .detail-guider-avatar {
    flex-shrink: 0;
    width: 40rpx;
    height: 40rpx;
    margin-left: 20rpx;
    border-radius: 50%;
    border: 2rpx solid #dbdbdb;
  }

  .detail-guider-name {
    margin-left: 20rpx;
    color: #2d2d2d;
  }

  .detail-guider-desc {
    flex-grow: 1;
    min-width: 0;
    font-size: 24rpx;
    color: #666666;
    line-height: 34rpx;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}

.detail-intro {
  padding: 40rpx 30rpx 30rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;

  .detail-intro-title {
    margin-bottom: 30rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 48rpx;
    font-weight: bold;
  }

  .detail-intro-html {
    color: #666666;
    overflow: hidden;
  }

  .detail-intro-img {
    width: 100%;
  }
}

.detail-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  height: 120rpx;
  padding-left: 30rpx;
  padding-right: 30rpx;
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #ffffff;

  .detail-fixed-menu {
    position: relative;
    flex-shrink: 0;
  }

  .detail-fixed-btn {
    flex-grow: 1;
    min-width: 0;
    margin-left: 30rpx;
  }
}
</style>